/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : '操作step',
			type : 'LineEdit',
			property : {tool_tip : '操作step,默认是net'},
		},
		{
			name : 'cutting_marign',
			title : '切除profile外数值',
			type : 'LineEdit',
			property : {tool_tip : '切除profile外数值,默认是100'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-20 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 删除板外 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 切除值 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>删除板外");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step:"unit.+",
		step2:"unit",
		cutting_marign: "200",
		auto_save: "No",
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	// 通过matrix获取board层
	var outline_layer = ["gko","gm1","ol"]

	var matrix = GEN.getMatrix({job:job})
	var board_layers = Object.keys(matrix).reduce(function(a,b){
		if(matrix[b].context == "board" && outline_layer.indexOf(b)<0){
			a.push(b)
		}
		return a
	},[])
	var all_layers = Object.keys(matrix)
	outline_layer = outline_layer.filter(function(v){
		return all_layers.indexOf(v) >=0
	})
	// 影响board层
	var steplist = GEN.getStepList({job:job})
	steplist = steplist.filter(function(v){
		var tmpreg = new RegExp(par.step,"ig")
		return tmpreg.test(v)
	})
	if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	steplist.forEach(function(step){
		GEN.openStep({job:job,name:step})
		GEN.units({type:"mm"})
		var outline_tmp = "outline_tmp"
		// 创建outline参考层
		if(GEN.isLayerExists({job:job,layer:outline_tmp})){
			GEN.deleteLayer({job:job, layer:outline_tmp})
		}
		GEN.COM("profile_to_rout,layer="+outline_tmp+",width=1")
		GEN.clearLayers()
		// 切除profile以外0.2mm（cutting_marign）物件
		GEN.affectedLayer({affected:"no", mode: "all"})
		GEN.affectedLayer({affected:'yes',layer:board_layers})
		// GEN.selectByFilter({profile:"out"})
		// if(GEN.getSelectCount()>0){GEN.selDelete()}
		GEN.COM("clip_area_strt")
		GEN.COM("clip_area_end,layers_mode=affected_layers,layer=,area=profile,area_type=rectangle,inout=outside,contour_cut=yes,margin="+par.cutting_marign+",feat_types=line\;pad\;surface\;arc\;text")


		// board_layers.forEach(function(layer){
		// 	if (outline_layer.indexOf(layer)<0){
		// 		GEN.affectedLayer({affected:"no", mode: "all"})
		// 		// GEN.workLayer({name:layer,display_number:1,clear_before:'yes'});
		// 		// GEN.clipArea({layers_mode:'affected_layers',area:'profile',inout:'outside',margin:0,contour_cut:'no'});
		// 		GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
		// 		GEN.selectByFilter({profile:"out"})
		// 		// GEN.selRefFeat({layers:outline_tmp,use:'filter',mode:'include'});
		// 		if(GEN.getSelectCount()>0){GEN.selDelete()}

		// 		GEN.COM("clip_area_strt")
		// 		GEN.COM("clip_area_end,layers_mode=affected_layers,layer=,area=profile,area_type=rectangle,inout=outside,contour_cut=yes,margin=200,feat_types=line\;pad\;surface\;arc\;text")

		// 		// var outline_ref = 'ol_tl_tmp';
		// 		// var tmp_work_layer = '_tmp_work_layer';
		// 		// if(GEN.isLayerExists({job:job,layer:tmp_work_layer})){
		// 		// 	GEN.deleteLayer({job:job,layer:[tmp_work_layer],step:step})
		// 		// }
		// 		// if(GEN.isLayerExists({job:job,layer:outline_ref})){
		// 		// 	GEN.deleteLayer({job:job,layer:[outline_ref],step:step})
		// 		// }
		// 		// GEN.createLayer({job:job,layer:tmp_work_layer,conext:'misc',type:'document',delete_exists:"yes"})
		// 		// GEN.createLayer({job:job,layer:outline_ref,conext:'misc',type:'document',delete_exists:"yes"})
		// 		// GEN.workLayer({name:outline_tmp,display_number:2,clear_before:'yes'})
		// 		// GEN.selCopyOther({dest:'layer_name',target_layer:outline_ref,invert:'no',dx:0,dy:0,size:0})
		// 		// GEN.affectedLayer({affected:'yes',layer:[outline_ref],clear_before:'yes'});
		// 		// GEN.COM('sel_resize',{size:200,corner_ctl:'no'});
		// 		// GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
		// 		// GEN.selRefFeat({layers:outline_ref,use:'filter',mode:'cover'});
		// 		// if ( GEN.getSelectCount() > 0 ) {
		// 		// 	GEN.selCopyOther({dest:'layer_name',target_layer:tmp_work_layer,invert:'no',dx:0,dy:0,size:0});
		// 		// 	GEN.affectedLayer({affected:'yes',mode:'single',layer:tmp_work_layer,clear_before:'yes'});
		// 		// 	GEN.COM('sel_all_feat');
		// 		// 	GEN.selChangeSym({symbol:'r1'});
		// 		// 	GEN.affectedLayer({affected:'yes',mode:'single',layer:outline_ref,clear_before:'yes'});
		// 		// 	GEN.COM('sel_all_feat');
		// 		// 	GEN.selChangeSym({symbol:'r2'});
		// 		// 	GEN.affectedLayer({affected:'yes',mode:'single',layer:tmp_work_layer,clear_before:'yes'});
		// 		// 	GEN.selRefFeat({layers:outline_ref,use:'filter',mode:'cover'});
		// 		// 	GEN.selReverse();
		// 		// 	if ( GEN.getSelectCount() > 0 ){GEN.selDelete() };
		// 		// 	GEN.affectedLayer({affected:'yes',mode:'single',layer:layer,clear_before:'yes'});
		// 		// 	GEN.selRefFeat({layers:tmp_work_layer,use:'filter',mode:'include'});
		// 		// 	if ( GEN.getSelectCount() > 0 ){GEN.selDelete() };
		// 		// }
		// 		// GEN.deleteLayer({job:job,layer:[outline_ref,tmp_work_layer]});
		// 	}
		// })
		GEN.affectedLayer({affected:'no',mode:'all'})
		GEN.deleteLayer({job:job,layer:[outline_tmp]})
	})

	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}
    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}


